import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 药品日志类型定义
 */
export interface LogMed {
  id: number
  medicineId: number
  medicineName: string
  patientId: number
  patientName: string
  doctorId: number
  quantity: number
  unit: string
  usage: string
  frequency: string
  hospitalizationId?: number
  logTime: string
  createTime: string
}

/**
 * 药品日志查询参数
 */
export interface LogMedSearchParams extends PageParams {
  medicineName?: string
  patientName?: string
  doctorId?: number
  startTime?: string
  endTime?: string
}

/**
 * 获取药品日志列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchLogMeds = async (params: LogMedSearchParams): Promise<PageResult<LogMed>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<LogMed>>>('/api/log-meds', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取药品日志失败')
    throw error
  }
}

/**
 * 获取药品日志详情
 * @param id 日志ID
 * @returns 日志详情
 */
export const getLogMed = async (id: number): Promise<LogMed> => {
  try {
    const { data } = await request.get<BaseResponse<LogMed>>(`/api/log-meds/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取药品日志详情失败')
    throw error
  }
}

/**
 * 创建药品日志
 * @param data 日志数据
 * @returns 创建的日志信息
 */
export const createLogMed = async (data: Omit<LogMed, 'id'>): Promise<LogMed> => {
  try {
    const { data: response } = await request.post<BaseResponse<LogMed>>('/api/log-meds', data)
    ElMessage.success('记录药品日志成功')
    return response.data
  } catch (error) {
    ElMessage.error('记录药品日志失败')
    throw error
  }
}

/**
 * 批量创建药品日志
 * @param items 日志数据数组
 */
export const batchCreateLogMeds = async (items: Omit<LogMed, 'id'>[]): Promise<void> => {
  try {
    await request.post('/api/log-meds/batch', { items })
    ElMessage.success(`成功记录${items.length}条药品日志`)
  } catch (error) {
    ElMessage.error('批量记录药品日志失败')
    throw error
  }
}

// 缓存最近请求的日志数据
const logMedCache = new Map<number, LogMed>()

/**
 * 获取药品日志详情（带缓存）
 * @param id 日志ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 日志详情
 */
export const getLogMedWithCache = async (id: number, forceRefresh = false): Promise<LogMed> => {
  if (!forceRefresh && logMedCache.has(id)) {
    return logMedCache.get(id)!
  }

  const logMed = await getLogMed(id)
  logMedCache.set(id, logMed)
  return logMed
}
